package com.lcq.gulimall.product.service.impl;

import com.lcq.common.constant.ProductConstant;
import com.lcq.common.to.SkuCouponTo;
import com.lcq.common.to.SkuSearchInfoTo;
import com.lcq.common.to.SpuBoundsTo;
import com.lcq.common.utils.R;
import com.lcq.gulimall.product.entity.*;
import com.lcq.gulimall.product.feign.CouponFeignService;
import com.lcq.gulimall.product.feign.SearchFeignService;
import com.lcq.gulimall.product.feign.WareFeignService;
import com.lcq.gulimall.product.service.*;
import com.lcq.gulimall.product.vo.*;
import com.mysql.cj.util.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lcq.common.utils.PageUtils;
import com.lcq.common.utils.Query;

import com.lcq.gulimall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {
    @Autowired
    SpuInfoDescService spuInfoDescService;

    @Autowired
    SpuImagesService spuImagesService;

    @Autowired
    ProductAttrValueService productAttrValueService;

    @Autowired
    AttrService attrService;

    @Autowired
    SkuInfoService skuInfoService;

    @Autowired
    SkuImagesService skuImagesService;

    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    CouponFeignService couponFeignService;

    @Autowired
    SearchFeignService searchFeignService;

    @Autowired
    BrandService brandService;

    @Autowired
    CategoryService categoryService;

    @Autowired
    WareFeignService wareFeignService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        /**
         * status: 0
         * key: mate
         * brandId: 8
         * catelogId: 225
         * */
        QueryWrapper<SpuInfoEntity> query = new QueryWrapper<>();
        String catelogId = (String) params.get("catelogId");
        if(!StringUtils.isNullOrEmpty(catelogId)&&Long.valueOf(catelogId)!=0){
            query.and((q)->{
                q.eq("catalog_id",catelogId);
            });
        }

        String brandId = (String) params.get("brandId");
        if(!StringUtils.isNullOrEmpty(brandId)&&Long.valueOf(brandId)!=0){
            query.and((q)->{
                q.eq("brand_id",brandId);
            });
        }

        String status = (String) params.get("status");
        if(!StringUtils.isNullOrEmpty(status)){
            query.and((q)->{
                q.eq("publish_status",status);
            });
        }

        String key = (String) params.get("key");
        if(!StringUtils.isNullOrEmpty(key)){
            query.and((q)->{
                q.like("spu_name",key).or().like("spu_description",key);
            });
        }

        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                query
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void save(SpuSaveVo spuSaveVo) {
        /**
         * 1、保存spu基本信息   pms_spu_info
         * 2、保存spu的描述图片  pms_spu_info_desc
         * 3、保存spu的图片集    pms_spu_images
         * 4、保存spu的规格参数   pms_sku_sale_attr_value
         * 5、保存spu的积分信息   sms_spu_bounds
         * 6、保存spu对应的sku信息
         * 	6.1、sku基本信息   pms_sku_info
         * 	6.2、sku图片信息   pms_sku_images
         * 	6.3、sku销售属性信息 pms_sku_sale_attr_value
         * 	6.4、sku满减优惠、满减等信息 sms_sku_ladder/sms_sku_full_reduction
         * */

        /**
         * 1、保存spu基本信息   pms_spu_info
         * */
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        BeanUtils.copyProperties(spuSaveVo,spuInfoEntity);
        this.save(spuInfoEntity);

        /**
         * 2、保存spu的描述图片  pms_spu_info_desc
         * */
        List descript = spuSaveVo.getDecript();
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
        spuInfoDescEntity.setDecript(String.join(",",descript));
        spuInfoDescService.save(spuInfoDescEntity);

        /**
         * 3、保存spu的图片集    pms_spu_images
         * */
        List<String> images = spuSaveVo.getImages();
        if(images!=null&&images.size()>0){
            List<SpuImagesEntity> imagesEntities = images.stream().map((image)->{
                SpuImagesEntity entity = new SpuImagesEntity();
                entity.setSpuId(spuInfoEntity.getId());
                entity.setImgUrl(image);
                return entity;
            }).collect(Collectors.toList());
            spuImagesService.saveBatch(imagesEntities);
        }
        /**
         * 4、保存spu的规格参数   pms_product_attr_value
         * */
        List<BaseAttrs> baseAttrs =  spuSaveVo.getBaseAttrs();
        if(baseAttrs!=null&&baseAttrs.size()>0){
            List<ProductAttrValueEntity> baseAttrsEntities = baseAttrs.stream().map((attr)->{
                ProductAttrValueEntity entity = new ProductAttrValueEntity();
                entity.setSpuId(spuInfoEntity.getId());
                entity.setAttrId(attr.getAttrId());
                entity.setAttrValue(attr.getAttrValues());
                entity.setQuickShow(attr.getShowDesc());
                entity.setAttrName(attrService.getById(entity.getAttrId()).getAttrName());
                return entity;
            }).collect(Collectors.toList());
            productAttrValueService.saveBatch(baseAttrsEntities);
        }

        /**
         * 5、保存spu的积分信息   sms_spu_bounds
         * */
        Bounds bounds = spuSaveVo.getBounds();
        if(bounds!=null){
            SpuBoundsTo spuBoundsTo = new SpuBoundsTo();
            spuBoundsTo.setBuyBounds(bounds.getBuyBounds());
            spuBoundsTo.setGrowBounds(bounds.getGrowBounds());
            spuBoundsTo.setSpuId(spuInfoEntity.getId());
            couponFeignService.saveSpuBounds(spuBoundsTo);
        }

        /**
         * 6、保存spu对应的sku信息
         * 	6.1、sku基本信息   pms_sku_info
         * 	6.2、sku图片信息   pms_sku_images
         * 	6.3、sku销售属性信息 pms_sku_sale_attr_value
         * 	6.4、sku满减优惠、满减等信息 sms_sku_ladder/sms_sku_full_reduction/sms_member_price
         * */
        List<Skus> skus = spuSaveVo.getSkus();
        if(skus!=null&&skus.size()>0){
            skus.stream().forEach((sku)->{
                String defaultImage = "";
                for (Images img: sku.getImages()) {
                    if(img.getDefaultImg()==1){
                        defaultImage = img.getImgUrl();
                    }
                }
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                skuInfoEntity.setPrice(sku.getPrice());
                skuInfoEntity.setSkuName(sku.getSkuName());
                skuInfoEntity.setSkuTitle(sku.getSkuTitle());
                skuInfoEntity.setSkuSubtitle(sku.getSkuSubtitle());
                skuInfoEntity.setSkuDefaultImg(defaultImage);
                skuInfoEntity.setCatalogId(spuSaveVo.getCatalogId());
                skuInfoEntity.setBrandId(spuSaveVo.getBrandId());
                skuInfoService.save(skuInfoEntity);
                skuImagesService.saveImages(skuInfoEntity.getSkuId(),sku.getImages());
                skuSaleAttrValueService.saveSaleAttrs(skuInfoEntity.getSkuId(),sku.getAttr());

                SkuCouponTo skuCouponTo = new SkuCouponTo();
                BeanUtils.copyProperties(sku,skuCouponTo);
                skuCouponTo.setSkuId(skuInfoEntity.getSkuId());
                couponFeignService.saveSkuCoupon(skuCouponTo);
            });
        }



    }

    @Transactional
    @Override
    public void up(Long spuId) throws IOException {
        if(spuId==null||spuId<=0){
            return;
        }

        List<SkuInfoEntity> skuList = skuInfoService.getBaseMapper().selectList(new QueryWrapper<SkuInfoEntity>().eq("spu_id", spuId));
        if(skuList==null||skuList.size()==0){
            return;
        }

        SpuInfoEntity spuInfoEntity = this.getById(spuId);
        if(spuInfoEntity==null){
            return;
        }

        BrandEntity brandEntity = brandService.getById(spuInfoEntity.getBrandId());
        CategoryEntity categoryEntity = categoryService.getById(spuInfoEntity.getCatalogId());
        List<ProductAttrValueEntity> entities = productAttrValueService.getBaseMapper()
                .selectList(new QueryWrapper<ProductAttrValueEntity>().eq("spu_id", spuId));
        List<SkuSearchInfoTo.Attr> attrs = null;
        if(entities!=null&&entities.size()>0){
            attrs = entities.stream().map(e -> {
                SkuSearchInfoTo.Attr attr = new SkuSearchInfoTo.Attr();
                BeanUtils.copyProperties(e,attr);
                return attr;
            }).collect(Collectors.toList());
        }

        List<SkuSearchInfoTo.Attr> finalAttrs = attrs;
        List<SkuSearchInfoTo> infoTos = skuList.stream().map(e -> {
            SkuSearchInfoTo infoTo = new SkuSearchInfoTo();
            BeanUtils.copyProperties(e,infoTo);
            infoTo.setSkuPrice(e.getPrice());
            infoTo.setSkuImg(e.getSkuDefaultImg());
            infoTo.setBrandImg(brandEntity.getLogo());
            infoTo.setBrandName(brandEntity.getName());
            infoTo.setCatalogName(categoryEntity.getName());
            infoTo.setAttrs(finalAttrs);
            /**
             * private Long hotScore;
             * */
            try {
                R r = wareFeignService.hasStock(e.getSkuId());
                infoTo.setHasStock((Boolean) r.get("hasStock"));
            }catch (Exception exception){
                log.error("skuId:"+e.getSkuId()+"查询库存失败,msg:"+exception.getMessage());
            }

            return infoTo;
        }).collect(Collectors.toList());


        try {
            searchFeignService.up(infoTos);
        } catch (IOException e) {
            log.error("商品上架失败");
            throw e;
        }

        spuInfoEntity.setPublishStatus(ProductConstant.SpuPublishStatusEnum.UP.getCode());
        this.updateById(spuInfoEntity);
    }
}